package com.gzh.demo.controller;

import com.gzh.demo.client.UserClient;
import com.gzh.demo.pojo.User;
import com.netflix.discovery.converters.Auto;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@Controller
//@DefaultProperties(defaultFallback = "defaultFallback")   //设置全局熔断方法！
public class UserController {

//    @Autowired
//    RestTemplate restTemplate;

//    @Autowired
//    DiscoveryClient discoveryClient;
    @Autowired
    UserClient userClient;


    @GetMapping("/find")
    @ResponseBody
//    @HystrixCommand(fallbackMethod = "queryUserById")
    public String getUser(@RequestParam("id") int id){
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
//        ServiceInstance serviceInstance = instances.get(0);
//        URI uri = serviceInstance.getUri();

        /**
         * 这个id=1的时候会熔断，访问其他的时候会拦截少部分如果正常则放行；
         */
//        if (id==1){
//            throw new RuntimeException();
//        }
//
//        String user = restTemplate.getForObject("http://service-provider/getUserById/" + id, String.class);
//        return user;
        User user = userClient.queryById(id);
        String s = user.toString();
        return s;

    }

//    public String defaultFallback(){
//        return "全局熔断默认设置！";
//    }
//
//    public String queryUserById(int id){
//        return "服务器忙请稍后再试！！";
//    }

}
